package com.ai3d.rfid.common.widget

import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.bj.ski.base.R

/**
 * @ProjectName : Trias
 * @Author : weijinsong
 * @Time : 2022/10/11 16:35
 * @Description : 倒计时Button
 */
class TimerButton(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
    private var textStr = ""
    private val textColor by lazy { textColors }
    private val duration: Long     //计时总长,默认120s

    init {
        isAllCaps = false   //字母小写
        //解析自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.TimerButton)
        duration = (1000 * typedArray.getInteger(R.styleable.TimerButton_duration, 60)).toLong()
        typedArray.recycle()
        textStr = text.toString()
    }

    //按钮封装了一个 CountDownTimer，它来帮我们计时
    private val countDownTimer: CountDownTimer by lazy {
        object : CountDownTimer(duration, 1) {
            override fun onFinish() {
                isEnabled = true
                if (duration == 60L * 1000) {
                    text = textStr
                }
                setTextColor(ContextCompat.getColor(context, R.color.white))
                timerLister?.onFinish()

            }

            override fun onTick(t: Long) {
                text = (t / 1000).toString() + " s"
                setTextColor(ContextCompat.getColor(context, R.color.white))
            }
        }
    }

    /**
     * 开始倒计时,同时按钮不可按
     */
    fun startTimer() {
        isEnabled = false
        countDownTimer.start()
        timerLister?.onStart()
    }

    fun cancelTimer() {
        countDownTimer.cancel()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        countDownTimer.cancel()   //防止内存泄漏
    }

    var timerLister: TimerLister? = null

    interface TimerLister {
        fun onStart()

        fun onFinish()
    }
}